<?php
namespace service\services;

use service\entity\User;
use service\org\util\TpString;
use  think\Db;
use think\Log;
use  service\algo\AlgoLogic;
use think\Request;


class UserService extends BaseUserService
{

    public function __construct()
    {

    }


    /**
     * @api {api} /UserService/call_loginAuthorize 用户统一登陆api
     * @apiVersion 0.0.1
     * @apiName  call_loginAuthorize  用户登录
     * @apiGroup UserService
     * @apiParam {String} user_name   用户名 .
     * @apiParam {String} password  密码.
     * @apiParam {String} user_type  用户类型  5：学生 2：课程设计师 3：加盟校管理员 4：教师
     * @apiSuccess {String} code   状态值.
     * @apiSuccess {Array} data   会员数据的数组.
     * @apiSuccess {String} msg   消息类型.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *           'code' => 1
     *           'data' => Array
     *              ｛
     *                'user_id' => 4334
     *                'user_name' => yixue123
     *                'real_name' => yixue123
     *                 'school_id' => 1
     *                 'school_sn' => sh1
     *                 'school_name' => 智适应教育上海总部
     *                 'last_login_time' => 1477474158
     *                  'last_login_ip' => 116.226.37.252
     *               ｝
     *          'msg' => success
     *
     *     }
     */
    private static function call_loginAuthorize($user_name, $password, $user_type = 5)
    {
        $param['user_name'] = $user_name;
        $param['password'] = $password;
        $param['user_type'] = $user_type;
        ksort($param);
        $key = implode(";", $param);
        $key = $key . self::$api_auth_key;
        $key = md5($key);
        $param['key'] = $key;
        $url = self::$api_auth_url;
        $return_data = rpc_request($url, $param);
        return $return_data;
    }

    public function loginIn($username, $password)
    {
        $return_data = array(
            'isSuccess' => '',
            'err_code' => '',
            'err_info' => ''
        );
        $user = self::call_loginAuthorize($username, $password);
        if ($user['data']['user_id'] && $user['data']['user_name']) {
            $return_data['isSuccess'] = 1;
            $return_data['err_info'] = "登陆成功";
            $data = array(
                "user_id" => $user['data']['user_id'],
                "username" => $user['data']['user_name']
            );
            $this->setUserSessionInfo($data);
        } else {
            $return_data['isSuccess'] = 0;
            $return_data['err_info'] = "用户或者密码错误";
        }
        return $return_data;

    }

    public function loginInTest($username, $password)
    {
        $return_data = array(
            'isSuccess' => '',
            'err_code' => '',
            'err_info' => ''
        );
//        $user = User::get(['username' => $username,'code'=>$password]);
        $user = User::get(['username' => $username]);
        if ($user) {
            if ($user && $user->status == 0) {
                $return_data['isSuccess'] = 0;
                $return_data['err_info'] = "您的帐号处于冻结状态，请联系管理员解冻！";
            } elseif ($user && $user->status == 1) {
                if (md5($password . $user->code) != $user->password) {
                    $return_data['isSuccess'] = 0;
                    $return_data['err_info'] = "用户密码错误";
                } else {
                    $return_data['isSuccess'] = 1;

                    $data = array(
                        "user_id" => $user->id,
                        "username" => $user->username,
                        "topic_id" => 9,//topicId默认为1
                    );
                    $this->setUserSessionInfo($data);
                }
            }
        } else {
            $return_data['isSuccess'] = 0;
            $return_data['err_info'] = "用户不存在";
        }

        return $return_data;

    }


    /**
     * 获取用户的SESSION信息
     */
    public function getUserSession()
    {

        $user_info = session('userInfo');
        return $user_info;

    }


    /**
     * 销毁用户的session信息.
     */
    public function destroyUserSession()
    {
        session('userInfo', null);
    }

    /**
     * 批量添加账号.
     */
    public function batchAddAccount()
    {
        $String = new TPString();
        for ($i = 1; $i <= 150; $i++) {
            $user = new User();
            if (strlen($i) == 1) {
                $username = 'test0' . $i;
            } else {
                $username = 'test' . $i;
            }
            $round_string = $String->randString(4, -1);
            $user->username = $username;
            $user->password = md5("123" . $round_string);
            $user->code = $round_string;
            $user->status = 1;
            $user->type = 3;
            $user->ctime = time();
            $user->remark = "测试帐号";
            $user->save();
        }
    }

    /**
     * 用户在单独的模块下,某知识点做的题数.
     * @param $user_id
     * @param $topicId
     * @param $module_type
     * @param $tag_code
     * @return mixed
     */
    public function getUserHasAnsweredNumForTagCode($user_id, $topicId, $module_type, $tag_code)
    {
        if (!$user_id) {
            $userInfo = session('userInfo');
            $user_id = $userInfo['user_id'];
        }
        $where['user_id'] = $user_id;
        $where['topicId'] = $topicId;
        $where['module_type'] = $module_type;
        $where['tag_code'] = $tag_code;
        $answeredInfo = Db::name('user_exam_detail')->where($where)->select();
//        echo Db::name('user_exam_detail')->getLastSql();

        $num = count($answeredInfo);
        return $num;
    }


    /**
     * 根据模块获取用户在某模块下已做题数.
     * @param null $user_id
     * @param $topicId
     * @param $module_type
     * @return array
     */
    public function getUserHasAnsweredQuestionsByModule($user_id = null, $topicId, $module_type=null,$class_id=null)
    {

        $return_arr = array();
        if (!$user_id) {
            $user_id = $this->getUserId();
        }
        $where['user_id'] = $user_id;
        if($topicId)
        {
            $where['topicId'] = $topicId;
        }

        if($class_id)
        {
            $where['class_id'] = $class_id;
        }

        if($module_type)
        {
            $where['module_type'] = $module_type;
        }

        $answeredInfo = Db::name('user_exam_detail')->where($where)->select();
        $question_service = new QuestionService();

        $kmap_code = config("kmap_code");
        foreach ($answeredInfo as $key => $val) {
//            $return_arr[$key]['question_id'] = $val['question_id'];
            $return_info = array();
            $return_info = $question_service->getQuestionById($val['question_id']);
            $return_info['tag_code'] = $val['tag_code'];
            $return_info['module_type'] = $val['module_type'];
            $return_info['right_answer'] = $val['right_answer'];
            $return_info['user_answer'] = $val['user_answer'];
            $return_info['stime'] = $val['stime'];
            $return_info['ctime'] = $val['ctime'];
            $tag = $question_service->getKnowlegeCode($kmap_code, $val['tag_code']);
            $return_info['tag_name'] = $tag["name"];
            $return_info['is_view_analyze'] = $val["is_view_analyze"];
            $return_info['is_view_answer'] = $val["is_view_answer"];
            $return_info['exam_detail_id'] = $val["id"];


            $return_info['right_answer_base64'] = $val['right_answer_base64'];

            // $return_info['user_answer_base64'] = $val['user_answer_base64'];

            $userAnswerBase64Arr = [];
            if ($val['user_answer_base64']) {
                $userAnswerBase64Arr = explode("@@@", $val['user_answer_base64']);

            }

            $return_info['user_answer_base64'] = $userAnswerBase64Arr;


            $return_info['is_right'] = $val['is_right'];
            $return_arr[] = $return_info;
//            $return_arr[$key]['is_right'] = $val['is_right'];
        }

        return $return_arr;
    }


    /**
     * 获取用户最后一个试题的答的对错.
     */
    public function getUserLastAnswerIsRight($user_id = null, $topicId, $module_type)
    {
        if (!$user_id) {
            $user_id = $this->getUserId();
        }
        $where['topicId'] = $topicId;
        $where['module_type'] = $module_type;
        $where['user_id'] = $user_id;
        $return_data = Db::name('user_exam_detail')->field('is_right')->where($where)->order("id desc")->find();
        if (empty($return_data)) {
            $is_right = 0;
        } else {
            $is_right = $return_data['is_right'];
        }
        return $is_right;
    }


    /**
     *
     * 获得某专题下的用户能力平均值.
     */
    public function getAverageNumOfKnowledgeByTopicId($topicId, $module_type)
    {
        $where['topicId'] = $topicId;
        $where['module_type'] = $module_type;
        $return_data = Db::name('user_ability_status')->field('weak_elements')->where($where)->select();
        $total_users = count($return_data);
        $kmap_code = config("kmap_code");
        $question_service = new QuestionService();
        $all_knowledgeList = $question_service->getKnowledgeList();
        $knowledgeList = $all_knowledgeList[$kmap_code];
        $total_knowledge_num = count($knowledgeList);  //总知识点数量.
        $good_total = 0;
        foreach ($return_data as $key => $val) {
            $weak_elements = json_decode($val['weak_elements']);
            $weak_num = count($weak_elements);
            $good_num = $total_knowledge_num - $weak_num;
            $good_total += $good_num;
        }
//        $average_num = $good_total / $total_users;
        $average_num = 6;
        return ceil($average_num);
    }


    public function getUserAverageAbility($user_id = null, $topicId, $module_type)
    {
        if (!$user_id) {
            $user_id = $this->getUserId();
        }
        $where['user_id'] = $user_id;
        $where['topicId'] = $topicId;
        $where['module_type'] = $module_type;
        $return_data = Db::name('user_ability')->field('ability')->where($where)->select();
        $num = count($return_data);
        $total_ability_num = 0;
        foreach ($return_data as $key => $val) {
            $total_ability_num += $val['ability'];
        }
        if($total_ability_num==0)return 0;
        $average_ability = $total_ability_num / $num;
        return $average_ability;
    }

    /**
     * 获取用户相关知识点的能力值
     * @param $user_id 用户id
     * @param $topicId 专题id
     * @param $module_type 模块类型
     * @return array
     */
    function getUserAbility($user_id, $topicId, $module_type)
    {
        if (!$user_id) {
            $user_id = $this->getUserId();
        }
        $where['user_id'] = $user_id;
        $where['topicId'] = $topicId;
        $where['module_type'] = $module_type;
        $return_data = Db::name('user_ability')->where($where)->column("ability", "tag_code");
        return $return_data;
    }

    /**
     * 插入user_exam_step_log 记录
     * @param type $topicId
     * @param type $module_type 专题类型
     * @return type
     */
    public function insertUserStep($topicId, $module_type, $has_learned_all_tag_code, $is_end = 1)
    {
        $user_id = $this->getUserId();
        $data['user_id'] = $user_id;
        $data['topicId'] = $topicId;
        $data['module_type'] = $module_type;
        $data['is_end'] = $is_end;
        $data['etime'] = time();
        $data['has_learned_all_tag_code'] = $has_learned_all_tag_code;
        $find_data = Db::name('user_exam_step_log')->where(['user_id' => $user_id, 'topicId' => $topicId, 'module_type' => $module_type, 'is_end' => $is_end])->field('id')->find();

        if ($find_data == false) {
            $id = Db::name('user_exam_step_log')->insert($data);
        } else {
            $id = $find_data['id'];
        }
        return $id;
    }

    /**
     * 查询一行user_exam_step_log 数据
     * @param type $where 查询条件
     * @return type
     */
    public function getUserStep($topicId, $user_id, $module_type = 1)
    {
        $where['topicId'] = $topicId;
        $where['user_id'] = $user_id;
        $where['module_type'] = $module_type;
        $row = Db::name('user_exam_step_log')->where($where)->field('is_end,module_type,has_learned_all_tag_code')->find();
        return $row;
    }

    /**
     * 查询多行user_exam_step_log 数据
     * @param type $where 查询条件
     * @return type
     */
    public function getListUserStep($topicId, $user_id, $module_type = 1)
    {
        $where['topicId'] = $topicId;
        $where['user_id'] = $user_id;
        $where['module_type'] = $module_type;
        $list = Db::name('user_exam_step_log')->where($where)->column('is_end,module_type,id,is_all_right,user_id,topicId', 'module_type');
        if ($list) {
            foreach ($list as $k => $v) {
                if ($v['is_end'] == '1' && $v['is_all_right'] == '0') {
                    $wrong_count = Db::name('user_exam_detail')->where(['topicId' => $v['topicId'], 'module_type' => $v['module_type'], 'is_right' => '0', 'user_id' => $v['user_id']])->count();
                    if ($wrong_count == 0) {
                        //错误数量=0 全对了更新
                        Db::name('user_exam_step_log')->where($v)->update(['is_all_right' => '1']);
                        $list[$k]['is_all_right'] = 1;
                    } else {
                        Db::name('user_exam_step_log')->where($v)->update(['is_all_right' => '2']);
                        $list[$k]['is_all_right'] = 2;
                    }
                    //查询是否全对  如果全对 更新当前字段is_all_right =1 否则更新当前字段为2
                }
            }
        }
        return $list;
    }

    /**
     * 获取用户的下一个边学边练的知识点.
     */
    public function getUserBxblNextTagCode($kmap_code, $topicId, $used_type)
    {
        //如果已做此知识点的题,已经学完应学的数量,即开始推下一个知识点.没有学完的话,即还是推此知识点.
        //获取用户做的最后一个知识点.
        Log::record("------" . __FUNCTION__ . "---topicId---" . $topicId);
        $tag_code = $this->getUserLastTagCodeOfBxbl($topicId);
        Log::record("------" . __FUNCTION__ . "---tag_code---" . $tag_code);
        $module_type = config('gaoxiao_module_type');
        $hasLeardTagCode = $this->getUserHasLearnedTagCode("", $topicId, $module_type);
        $learned_elements = array();
        foreach ($hasLeardTagCode as $key => $val) {
            $learned_elements[] = $val['tag_code'];
        }
        $algologic = new AlgoLogic();

        //如果没有知识点,说明用户第一次做.故直接从算法获取知识点.
        if (empty($tag_code)) {
            $return_tag_code = $algologic->get_bxbl_tagCode($kmap_code, $topicId, $used_type, $learned_elements);
            $tag_code = $return_tag_code['next_element'];
        } else {
            $return_data = $this->getUserHasAnsweredQuestions("", $tag_code, $topicId, $module_type);
            $num = count($return_data);
            Log::record("------" . __FUNCTION__ . "---num---" . $num);
            $need_num = config("to_learn_num");
            Log::record("------" . __FUNCTION__ . "---need_num---" . $need_num);
            if ($num >= $need_num) {
                $return_tag_code = $algologic->get_bxbl_tagCode($kmap_code, $topicId, $used_type, $learned_elements);
                $tag_code = $return_tag_code['next_element'];
            }
        }

        return $tag_code;
    }


    /**
     * 获取用户已答试题.
     * @param $user_id
     * @param $tag_code
     * @param $topicId
     * @param $module_type
     */
    public function getUserHasAnsweredQuestions($user_id, $tag_code, $topicId, $module_type)
    {
        if (!$user_id) {
            $user_id = $this->getUserId();
        }
        $where['tag_code'] = $tag_code;
        $where['topicId'] = $topicId;
        $where['module_type'] = $module_type;
        $where['user_id'] = $user_id;
        $return_data = Db::name('user_exam_detail')->where($where)->select();
        return $return_data;
    }

    /**
     * 根据特定条件获取用户已经学习的知识点.
     */
    public function getUserHasLearnedTagCode($user_id = null, $topicId, $module_type)
    {
        if (!$user_id) {
            $user_id = $this->getUserId();
        }
        $where['user_id'] = $user_id;
        $where['topicId'] = $topicId;
        $where['module_type'] = $module_type;
        $return_data = Db::name('user_exam')->where($where)->field("tag_code")->select();

//        echo Db::name('user_exam')->getLastSql();
        return $return_data;
    }


    /**
     * 获取用户边学边练的最后一个知识点.
     */
    public function getUserLastTagCodeOfBxbl($topicId)
    {
        $user_id = $this->getUserId();
        $where['user_id'] = $user_id;
        $where["topicId"] = $topicId;
        $where['module_type'] = config('gaoxiao_module_type');
        Log::record("------" . __FUNCTION__ . "---topicId---" . $topicId);
//        $return_data = Db::name('user_bxbl_question')->where($where)->field('tag_code')->order("id desc")->find();
        $return_data = Db::name('user_exam_detail')->where($where)->field('tag_code')->order("id desc")->find();
        if (empty($return_data)) {
            $tag_code = "";
        } else {
            $tag_code = $return_data['tag_code'];
        }
        Log::record("------" . __FUNCTION__ . "---tag_code---" . $tag_code);
        return $tag_code;
    }

    /**
     * 添加用户
     * @param $userName
     * @param $password
     * @param $isBatch 是否批量生成
     * @return int
     */
    public function addUser($userName, $password, $isBatch = 0, $total = 100, $type = 3)
    {
        $String = new TpString();
        $user = new User();


        if ($isBatch == 0) {
            $total = 1;
        }


        $remark = "测试账号";
        if ($type == 1) {
            $remark = "学生账号";
        }
        $data = [];

        for ($i = 1; $i <= $total; $i++) {
            $round_string = $String->randString(4, -1);
            $userPassword = md5($password . $round_string);

            if (strlen($i) == 1) {
                $username = $userName.'0' . $i;
            } else {
                $username = $userName.$i;
            }

            $data[] = array(
                "username" => $username,
                "password" => $userPassword,
                "code" => $round_string,
                "status" => 1,
                "type" => $type,
                "ctime" => time(),
                "remark" => $remark,
            );
        }
        $result = $user->saveAll($data);
        return $result;


    }

    /**
     * 未使用过的用户
     * @return mixed
     */
    public function unUsedUser($type, $param = null)
    {
        $map["user_id"] = array("exp", "is  null");
        if ($type) {
            $map["type"] = $type;
        }
        $result = Db::table('ct_user')
            ->alias('user')
            ->join(['user_exam_detail' => 'examDetail'], 'user.id = examDetail.user_id', 'Left')
            ->where($map)
            ->field("user.id,username,user.ctime,examDetail.user_id,user.status")
            ->order("user.id desc")//->fetchSql()
            ->paginate(config('list_rows'), false, array('query' => $param));
        return $result;

    }

    /**
     * 通过用户名查找用户
     * @param $userName
     *
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public function getUserByName($userName)
    {
        $user = new User();
        $map["username"] = $userName;
        $result = $user->db()->where($map)->find();
        return $result;
    }

    public function updateUserStepLog($user_id, $topicId, $module_type, $is_end)
    {
        if (!$user_id) {
            $user_id = $this->getUserId();
        }

        $user_id = $this->getUserId();
        $where['user_id'] = $user_id;
        $where['topicId'] = $topicId;
        $where['module_type'] = $module_type;
        $data['is_end'] = $is_end;
        $data['etime'] = time();
        Db::name('user_exam_step_log')->where($where)->update($data);
    }

    /**
     * 获取饼形数据 tag_info
     * @param type $module_type
     * @param type $topicId
     */
    public function getUserChartData($module_type = 1, $topicId = 9)
    {
        $question_service = new QuestionService();
        $user_id = $this->getUserId();
        $algoLogic = new AlgoLogic();
        $question_service = new QuestionService();
        $all_knowledgeList = $question_service->getKnowledgeList();
        $kmap_code = config("kmap_code");
        $knowledgeList = $all_knowledgeList[$kmap_code];
        $weakElements = $algoLogic->getWeakElements("", $topicId);
        foreach ($knowledgeList as $key => $knowledge) {
            $tag_code = $knowledge['code'];
            if (empty($weakElements)) {
                $knowledgeList[$key]['is_weak'] = 0;
            } else {
                if (in_array($tag_code, $weakElements)) {
                    $knowledgeList[$key]['is_weak'] = 1;
                } else {
                    $knowledgeList[$key]['is_weak'] = 0;
                }
            }

        }

        if (empty($weakElements)) {
            $need_toLearn_next_tag_name = "";
        } else {
            $need_toLearn_next_tag_code = $weakElements[0];
            foreach ($knowledgeList as $key => $val) {
                if ($val['code'] == $need_toLearn_next_tag_code) {
                    $need_toLearn_next_tag_name = $val['name'];
                }
            }
        }
        $total_knowledge_num = count($knowledgeList);  //总知识点数量.
        $weakElements_num = count($weakElements); //薄弱知识点数量.
        return $total_knowledge_num - $weakElements_num;
    }

    public function getZhlxUserChartData($topicId)
    {
        $xiance_module_type = config('xiance_module_type');
        $gaoxiao_module_type = config('gaoxiao_module_type');
        $zhlx_module_type = config('zonghe_module_type');
        $xiance = $this->getUserChartData($xiance_module_type, $topicId);
        $bxbl = $this->getUserChartData($gaoxiao_module_type, $topicId);
        $zhlx = $this->getUserChartData($zhlx_module_type, $topicId);
        $arr = array(
            array(
                'xiance_has_learned_num' => $xiance
            ),
            array(
                'zhlx_has_leared_num' => $bxbl
            ),
            array(
                'zhlx_not_leared_num' => $zhlx
            )
        );
        return $arr;
    }

    public function getUserIsAllRight($topicId, $module_type, $user_id)
    {
        $return = 0;
        $user_exam_step_log_end = Db::name('user_exam_step_log')->where(['topicId' => $topicId, 'module_type' => $module_type, 'user_id' => $user_id, 'is_end' => '1'])->count();//答题结束
        if ($user_exam_step_log_end > 0) {
            $is_right = Db::name('user_exam_detail')->where(['topicId' => $topicId, 'module_type' => $module_type, 'is_right' => '0', 'user_id' => $user_id])->count();//查询是否包含有错误的题 如果没有错误就是全部答对
            if ($is_right == 0) $return = 1;
        }
        return $return;
    }

    /**
     * 查看用户测试报告
     * @param     $userId 用户id
     * @param int $topicId 专题id
     * @param int $module_type 模块类型
     * @param int $submodule_type 子模块类型
     *
     * @return mixed
     */
    function getUserReport($userId, $topicId = 9, $module_type = null, $submodule_type = null, $isAll = false)
    {
        if ($userId !== null) {
            $map["user_id"] = $userId;
        }
        if ($topicId) {
            $map["topicId"] = $topicId;
        }
        if ($module_type !== null) {
            $map["module_type"] = $module_type;
        }
        if ($submodule_type !== null) {
            $map["submodule_type"] = $submodule_type;
        }

        $arr = [];
        if ($isAll) {
            $result = DB::name("user_exam_detail")->where($map)->select();
            $page = "";
        } else {
            $result = DB::name("user_exam_detail")->where($map)->paginate();
            $page = $result->render();
        }

        $questionService = new QuestionService();
        $all_knowledgeList = $questionService->getKnowledgeList();

        $kmap_code = config("kmap_code");
        $knowledgeList = $all_knowledgeList[$kmap_code];

        //dump($knowledgeList);die;
        $new_knowledgeList = [];
        foreach ($knowledgeList as $item) {
            $new_knowledgeList[$item["code"]] = $item["name"];
        }

        foreach ($result as $item) {
            $item["question"] = $questionService->getQuestionById($item["question_id"]);
            $item["tag_name"] = $new_knowledgeList[$item["tag_code"]];
            $item["q_type"] = $item["question"]["q_type"];
            $item["answer"] = $item["question"]["answer"];
            $item["answer_base64"] = $item["question"]["answer_base64"];

            $userAnswerBase64Arr = [];
            if ($item['user_answer_base64']) {
                $userAnswerBase64Arr = explode("@@@", $item['user_answer_base64']);
            }
            $item['user_answer_base64'] = $userAnswerBase64Arr;


            $arr[] = $item;
        }

        //dump($arr[0]);die;

        return ["data" => $arr, "page" => $page];


    }

    /**
     * 获取用户
     * @param null $userName
     * @param bool $isAll
     *
     * @return array
     */

    public function getUser($userName = null, $isAll = false)
    {

        $request = Request::instance();
        $param = $request->param();

        $map = [];
        if ($userName) {
            $map["username"] = array("like", "%$userName%");
        }
        if ($isAll) {
            $page="";
            $result = DB::name("user")->where($map)->order("id desc")->select();
        } else {

            $result = DB::name("user")->where($map)->order("id desc")->paginate(config('list_rows'), false, array('query' => $param));
            $page = $result->render();
        }


        return ["data" => $result, "page" => $page];
    }

    /*
     * 判断用户先行测试是否全对.
     */
    public function getUserXianceIsAllRight($topicId)
    {
        $user_id = $this->getUserId();
        $where['user_id'] = $user_id;
        $where['module_type'] = 1;
        $where['topicId'] = $topicId;
        $return_data = Db::name('user_exam_step_log')->field('is_all_right')->where($where)->find();
        if (!empty($return_data)) {
            $is_all_right = $return_data['is_all_right'];
        } else {
            $is_all_right = 0;
        }
        return $is_all_right;

    }

    /**
     * 获取用户边学边练的知识点.
     */
    public function getUserlearnedKnowledgeNum($topicId)
    {
        $user_id = $this->getUserId();
        $ability_standard = config("ability_standard");
        $sql = "select * from ct_user_ability where user_id = $user_id  and module_type = 2 and topicId = $topicId and ability>=$ability_standard";
        $has_learned_knowledge = Db::query($sql);
        $num = count($has_learned_knowledge);
        return $num;
    }


    /**
     * 获取用户边学边练知识点掌握对比例.
     */
    public function getUserLearnedKnowledgeScaleForBxbl($topicId)
    {
        $algoLogic = new AlgoLogic();
        $weakElements = $algoLogic->getWeakElements("", $topicId);
        $weakElements_num = count($weakElements);
        $haslearnedKnowledgeNum = $this->getUserlearnedKnowledgeNum($topicId);
        $sale = $haslearnedKnowledgeNum / $weakElements_num;
        return $sale;
    }

    static public function getUid($username)
    {
        $data = Db::name('user')->where(['username' => $username])->field('id')->find();
        if ($data['id'] == false) return -1;
        return $data['id'];
    }

    /**
     * 获取用户已经学过的知识点
     * @param $user_id
     * @param $topic_id
     * @param $module_type
     * @param $submodule_type
     *
     * @return float|int
     */
    public function getHaveLeardTagCode($user_id, $topic_id, $module_type)
    {

        if ($user_id) {
            $map["user_id"] = $user_id;
        }
        if ($topic_id) {
            $map["topicId"] = $topic_id;
        }
        if ($module_type) {

            $map["module_type"] = $module_type;
        }
        $haveLearnedWeakElements = Db::name('user_exam')->distinct("tag_code")->where($map)->field('tag_code')->column('tag_code');
        return $haveLearnedWeakElements;

    }

    public function getLearned_num($user_id, $topicId, $module_type)
    {
        $where = [];
        $where['user_id'] = $user_id;
        $where['topicId'] = $topicId;
        $where['module_type'] = $module_type;
        $data = Db::name('user_ability')->where($where)->where('ability>=0.8')->column('*', 'tag_code');
        return $data;
    }

    public function getLearned_nums($user_id, $topicId, $knowledgeList = [])
    {
        $data_bxbl = $this->getLearned_num($user_id, $topicId, config('gaoxiao_module_type'));
        $bxblLearned_num = count($data_bxbl);//边学边练攻克数量
        $zhlxLearned_nums = $this->getLearned_num($user_id, $topicId, config('zonghe_module_type'));
        $key_knowledgeList = [];
        foreach ($knowledgeList as $k => $v) {
            if (isset($v['code'])) $key_knowledgeList[] = $v['code'];
        }
        foreach ($zhlxLearned_nums as $k1 => $v1) {
            if (!in_array($k1, $key_knowledgeList)) {//综合练习知识点不在总的知识点的情况下排除
                unset($zhlxLearned_nums[$k1]);
            }
        }
        $zhlxLearned_num = count($zhlxLearned_nums);//综合练习在总的知识点的攻克数量
        return $bxblLearned_num + $zhlxLearned_num;
    }


    public function freezeUser($ids)
    {
        $model=new User();
        $map["id"]=array("in",$ids);
        $data["status"]=0;
        $result=$model->where($map)->update($data);
        return $result;
    }

    public function unFreezeUser($ids)
    {
        $model=new User();
        $map["id"]=array("in",$ids);
        $data["status"]=1;
        $result=$model->where($map)->update($data);
        return $result;
    }


}
